import java.util.concurrent.Semaphore;

//Semaphore 可以控制同时访问的线程个数，通过
//acquire() 获取一个许可，如果没有就等待，而 release() 释放一个许可。
public class SemaphoreDemo {

    public static void main(String[] args) {
        int n = 4;
        Semaphore semaphore = new Semaphore(n);
        for (int i = 0; i < 8; i++) {
            new Worker(i,semaphore).start();
        }

    }

    static class Worker extends Thread{
        private  int num;
        private Semaphore semaphore;

        public Worker(int num, Semaphore semaphore) {
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(num+"线程:获取信号量");
                Thread.sleep(5000);
                System.out.println(num+"线程执行结束，释放信号量");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
